Use Pre-request Script to Dynamically Add a Request Parameter
Usage Scenario
We may need to send some parameters when making a request, and these parameters are calculated from other request parameters. For example:
Interface: https://httpbin.org/anything
The body request parameters are as follows:
Parameter | Description |
---|---|
user_id | User ID |
nick_name | Username |
The header request parameters are as follows:
Parameter | Description |
---|---|
token | Composed of user_id and nick_name from the body request parameters through MD5 encryption |
In the above situation, we need to calculate a token from the body request parameters user_id and nick_name through MD5 encryption and put it in the header before sending. How does EchoAPI achieve this requirement?
We can achieve this by adding request parameters in the pre-execution script.
Specific Implementation
As shown in the figure, we have already added the parameters we need in the body.
1. Calculate the token and assign it to a variable
Next, we need to calculate the token through the pre-execution script and add it to the header parameters.
First, define a temporary variable raw_token in the pre-request script, whose value is
let raw_token = $.md5(request.request_bodys.user_id.toString() + request.request_bodys.nick_name.toString());
The meaning of this is: define a variable raw_token, whose value is equal to
$.md5(request.request_bodys.user_id + request.request_bodys.nick_name)
Note: $.md5 is the MD5 function built into the EchoAPI script. For more encryption functions, please refer to the "Using CryptoJS for MD5/AES Encryption and Decryption of Request Parameters" section.
2.Dynamically add request headers
pm.setRequestHeader("token", raw_token);
After sending, you can see that EchoAPI automatically added a request header token.
Appendix: request object
Get request parameters through the request object. For details, please refer to the "EchoAPI Built-in Variables" section of the document.